#include "subscriber_cache.h"
#include "base/logging.h"

namespace imserver {

bool SubscriberCache::Add(const std::string & session, HttpRequestPtr request) {
  std::map<std::string, HttpRequestPtr>::iterator it = cache_.find(session);
  if (it != cache_.end()) {
    LOG_WARN("SubscriberCache::Add duplicate id=" << request->effective_uid() << " session=" << session);
    return false;
  }

  cache_[session] = request;
  LOG_INFO("SubscriberCache::Add id=" << request->effective_uid() << " sess=" << session << " size=" << cache_.size());
  return true;
}

bool SubscriberCache::Remove(const std::string & session, HttpRequestPtr request) {
  std::map<std::string, HttpRequestPtr>::iterator it = cache_.find(session);
  if (it != cache_.end()) {
    if (it->second != request) {
      // 对已一个session有多个request的情况，会把其他的request也干掉
      LOG_WARN("SubscriberCache::Remove mismatch. uid=" << request->effective_uid() << " session=" << session);
    }
    cache_.erase(it);
    LOG_INFO("SubscriberCache::Remove ok. uid=" << request->effective_uid() << " session=" << session << " size=" << cache_.size());
    return true;
  }
  LOG_WARN("SubscriberCache::Remove err. uid=" << request->effective_uid() << " session=" << session << " not found");
  return false;
}

HttpRequestPtr SubscriberCache::Get(const std::string & session) {
  std::map<std::string, HttpRequestPtr>::iterator it = cache_.find(session);
  if (it != cache_.end()) {
    return it->second;
  }

  LOG_WARN("SubscriberCache session " << session << " not found.");
  return HttpRequestPtr(); 
}

void SubscriberCache::Dump() const {
  if (cache_.size() > 1000) {
    return;
  }
  std::map<std::string, HttpRequestPtr>::const_iterator it = cache_.begin();
  LOG_INFO("SubscriberCache dump BEGIN.");
  for(; it != cache_.end(); ++it) {
    LOG_INFO("SubscriberCache dump " << it->first);
  }
  LOG_INFO("SubscriberCache dump END.");
}

}

